package com.azunitech.jms.repos;

import java.util.Collection;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import com.azunitech.jms.common.domains.LocationVo;

public class PartsService extends ServiceBase {
	public PartsService(EntityManager em) {
		super(em);
	}

	public Parts createParts(String partNumber) {
		Parts parts = new Parts();
		parts.setId(partNumber);
		m_EntityManager.persist(parts);
		return parts;
	}

	public Parts createParts(String partNumber, Collection<LocationVo> locations ) {
		Parts parts = m_EntityManager.find(Parts.class, partNumber);
		if ( parts == null){
			parts = createParts(partNumber);
		}
		
		for( LocationVo locationVo : locations){
			String locationCode = locationVo.getLocationCode();
			Location location = m_EntityManager.find(Location.class, locationCode);
			if ( location == null){
				location = createLocation(locationCode,locationVo.getQuantity());
			}
			
			parts.addLoction(location);
		}
		return parts;
	}
	
	@SuppressWarnings("unchecked")
	public Collection<Parts> findAllParts() {
		Query query = m_EntityManager.createQuery("SELECT d FROM Parts d");
		return (Collection<Parts>) query.getResultList();
	}

	public Location createLocation(String locationCode, long quantity) {
		Location location = new Location();
		location.setId(locationCode);
		location.setQuantity(quantity);
		m_EntityManager.persist(location);
		return location;
	}

	public Location setLocationParts(String locationCode, String partNumber) {
		Location location = m_EntityManager.find(Location.class, partNumber);
		Parts parts = m_EntityManager.find(Parts.class, partNumber);
		parts.addLoction(location);
		return location;
	}

	@SuppressWarnings("unchecked")
	public Collection<Location> findAllLocations() {
		Query query = m_EntityManager.createQuery("SELECT e FROM Location e");
		return (Collection<Location>) query.getResultList();
	}
}
